package com.tjetc.utils;

import io.jsonwebtoken.*;

import java.security.SignatureException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class JwtUtil {
    private static String secret = "111222333";
    private static int time = 30 * 60 * 1000;

    //使用钥匙生成锁
    public static String createToken(Map<String, Object> map) {
        JwtBuilder builder = Jwts.builder();
        String token = builder
                //header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //payload
                .setClaims(map)//登录用户信息
                .setSubject("login") //主题信息
                .setId(UUID.randomUUID().toString())//id
                .setExpiration(new Date(System.currentTimeMillis() + time)) //过期时间
                //signature
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();//拼接成完整的串,这个串就是使用secret钥匙生成的锁token
        return token;
    }

    //解析锁取得payload
    public static Claims parseToken(String token) {
        //解析这把锁
        Claims body = null;//获取的是payload内容(map)
        try {
            body = Jwts.parser()
                    .setSigningKey(secret) //设置开锁的钥匙
                    .parseClaimsJws(token)  //使用secret钥匙加token这把锁
                    .getBody();
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
                 IllegalArgumentException e) {
            e.printStackTrace();
        }
        return body;
    }

    //验证锁是否有效
    public static boolean validToken(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(secret) //设置开锁的钥匙
                    .parseClaimsJws(token);  //使用secret钥匙加token这把锁
            return true;
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
                 IllegalArgumentException e) {
            e.printStackTrace();
        }
        return false;
    }
}
